package org.byqh.dqeai.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.byqh.dqeai.common.Json;
import org.byqh.dqeai.dto.SysOpLogDTO;
import org.byqh.dqeai.dto.common.IPage;
import org.byqh.dqeai.entity.EaiSysUser;
import org.byqh.dqeai.entity.SysOpLog;
import org.byqh.dqeai.entity.proxy.SysOpLogProxy;
import org.byqh.dqeai.util.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/sysOpLog")
@Tag(name = "系统[SysOpLog] - 操作日志管理")
public class SysOpLogController extends BaseController<SysOpLog, SysOpLogProxy> {
    @Autowired
    private EaiSysOrganizationController orgController;

    @Autowired
    private HttpServletRequest request;

    @Override
    @PostMapping(value = "/")
    public Json<Boolean> post(SysOpLog dto) {
        dto.setOpTime(LocalDateTime.now());
        dto.setUserIp(HttpUtils.getIp(request));

        EaiSysUser one = easyEntityQuery.queryable(EaiSysUser.class)
                .where(e -> e.userCode().eq(dto.getUserCode()))
                .firstOrNull();

        if (one != null) {
            dto.setUserName(one.getUserName());
            dto.setUserDept(orgController.GetPath(one.getOrgId()));
        }
        return super.post(dto);
    }

    /**
     * 分页查询数据
     */
    @PostMapping(value = "/list")
    public Json<IPage<SysOpLog>> list(@RequestParam(defaultValue = "1") Integer page,
                                      @RequestParam(defaultValue = "10") Integer size,
                                      @RequestParam(defaultValue = "", required = false) String sort,
                                      @RequestBody(required = false) SysOpLogDTO dto) {

        return listPageImpl(SysOpLog.class, page, size, (query) -> {
            if (dto != null) {
                if (!StringUtils.isBlank(dto.getAppId())) {
                    query = query.where(r -> r.appId().eq(dto.getAppId()));
                }

                if (!StringUtils.isBlank(dto.getKeyword())) {
                    String sqlUser = String.format(
                            "select user_code from eai_sys_user" +
                                    " where user_code like '%%%s%%'" +
                                    " or user_name like '%%%s%%'"
                            , dto.getKeyword(), dto.getKeyword());

                    query = query.where(r -> r.userCode().in(easyQueryClient.queryable(sqlUser, String.class)));
                }

                query = query.orderBy(r -> r.opTime().desc());
            }

            return query;
        });
    }
}